<!--动态发布-->
<template>
    <el-container id="app">
        <el-header>
            <div class="header-container">
                <a href=""><img src="../../assets/images/logo.png" class="logo"/></a>
                <el-page-header @back="back" :content="headerTitle" title="首页">
                </el-page-header>
            </div>


        </el-header>
        <el-main>
            <div class="add-dynamic container">
                <el-steps :active="activeStep" simple finish-status="success">
                    <el-step title="行业地区类型"></el-step>
                    <el-step title="行业属性"></el-step>
                    <el-step title="描述和图片"></el-step>
                    <el-step title="发布"></el-step>
                </el-steps>
                <el-row>
                    <el-col :span="19" :offset="2">
                        <div v-if="activeStep == 0">
                            <el-form ref="stepForm0" :model="dynamic" :rules="dynamicRules" size="small"
                                     label-width="90px"
                                     label-suffix=":"
                                     v-loading="loading">

                                <el-form-item label="类型" prop="type"
                                              :rules="{ required:true,message:'请选择类型', trigger: 'blur' }"
                                              v-if="type == null">
                                    <el-select v-model="dynamic.type" placeholder="请选择" @change="changHeader">
                                        <el-option v-for="type in typeList" :key="type.id" :value="type.id"
                                                   :label="type.name"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="所属行业" prop="industryCategory">
                                    <el-cascader
                                            v-model="dynamic.industryCategory"
                                            :options="industryCategoryData"
                                            :props="{ expandTrigger: 'hover',value:'code',label:'name',children:'sublist' }"></el-cascader>
                                </el-form-item>
                                <el-form-item label="地区" prop="area">
                                    <el-cascader
                                            v-model="dynamic.area"
                                            :options="areaList"
                                            :props="{ expandTrigger: 'hover',value:'code',label:'name',children:'sublist' }"></el-cascader>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="next">保存下一步</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div v-else-if="activeStep == 1">
                            <el-alert title="请注意填写相关信息，这有助于商友找到你" type="success" :closable="false"></el-alert>

                            <el-form ref="stepForm1" size="small" label-width="90px" :inline="true" :model="dynamic"
                                     class="attribute-form"
                                     label-suffix=":" v-loading="loading">
                                <el-form-item v-for="(attr,index) in attributeList" :key="attr.id" :label="attr.name"
                                              :prop="`${index}`"
                                              :rules="{ validator:validatorValue,required:attr.isRequired == 1 ? true : false, trigger: 'blur' }">
                                    <el-select v-model="attributeList[index].value" style="width: 215px"
                                               v-if="attr.valueType == 'select'">
                                        <el-option v-if="attr.dataList != undefined" v-for="d in attr.dataList"
                                                   :key="d.value" :value="d.id" :label="d.name"></el-option>
                                    </el-select>
                                    <el-input :type="attr.valueType" v-model="attributeList[index].value"
                                              style="width: 215px" v-else>
                                        <template slot="append" v-if="attr.unit">{{attr.unit}}</template>
                                    </el-input>
                                    <el-link :underline="false" v-if="attr.custom" @click="removeAttribute(index)"><i
                                            class="el-icon-delete"></i></el-link>
                                </el-form-item>

                                <el-form-item style="width: 100%;margin-top: 10px;margin-left: 90px">
                                    <el-button type="primary" @click="next">保存下一步</el-button>
                                    <el-button type="primary" @click="showAttribute">添加自定义属性</el-button>
                                    <el-button @click="pre">上一步</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div v-else-if="activeStep == 2">

                            <el-form ref="stepForm2" :model="dynamic" :rules="dynamicRules" size="small"
                                     label-width="90px" label-suffix=":">

                                <el-form-item label="标题" prop="title" size="medium">
                                    <el-input style="font-size: 16px" type="text" v-model="dynamic.title"
                                              :placeholder="placeholderList[dynamic.type - 1] + '，最多49个字符'">
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="详细描述" prop="content">
                                    <tinymce-editor v-model="dynamic.content" ref="editor"></tinymce-editor>
                                </el-form-item>
                                <el-form-item label="标签">
                                    <el-tag :key="tag" v-for="tag in tagList" closable :disable-transitions="false"
                                            @close="handleTagClose(tag)" type="info">{{tag}}
                                    </el-tag>
                                    <el-input class="input-new-tag" v-if="tagInputVisible" v-model="tagInputValue"
                                              ref="saveTagInput" @keyup.enter.native="handleTagInputConfirm"
                                              @blur="handleTagInputConfirm">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" @click="showTagInput" :plain="true">+ 添加
                                    </el-button>
                                    <div class="form-item-describe">最多添加5个标签</div>
                                </el-form-item>
                                <el-form-item label="发布形式">
                                    <el-radio-group v-model="dynamic.visibility">
                                        <el-radio label="1">公开</el-radio>
                                        <el-radio label="2">私密</el-radio>
                                        <el-radio label="3">粉丝可见</el-radio>
                                        <el-radio label="4">VIP可见</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <div style="padding-left: 90px">
                                    <el-alert title="温馨提示：请勿发布涉及政治、广告、营销、翻墙、违反国家法律法规等内容" type="error"></el-alert>
                                </div>
                                <el-form-item>
                                    <el-button type="primary" @click="next">保存下一步</el-button>
                                    <el-button @click="pre">上一步</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div v-else-if="activeStep == 3">
                            <el-form ref="stepForm3" :model="dynamic" size="small" label-width="90px" label-suffix=":">
                                <el-form-item label="自动关闭">
                                    <el-switch v-model="dynamic.delivery"></el-switch>
                                    <div class="form-item-describe">自动关闭后将无法再评论和点赞</div>
                                </el-form-item>
                                <el-form-item label="关闭时间" v-if="dynamic.delivery">
                                    <el-date-picker v-model="dynamic.closeTime"></el-date-picker>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="next" :loading="addLoading">保存上传</el-button>
                                    <el-button @click="pre">上一步</el-button>
                                </el-form-item>
                            </el-form>
                        </div>

                    </el-col>
                </el-row>
            </div>
            <el-dialog :visible.sync="visible" width="350px" :center="true" :close-on-click-modal="false"
                       :close-on-press-escape="false">
                <el-form ref="addAttributeForm" :model="attribute" size="small" label-width="70px"
                         :rules="addAttributeRules" class="add-attribute-form" label-suffix=":">
                    <el-form-item label="属性名" prop="name">
                        <el-input type="text" name="name" v-model="attribute.name"></el-input>
                    </el-form-item>
                    <el-form-item label="属性值" prop="value">
                        <el-input :type="attribute.type" name="value" v-model="attribute.value"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-select name="type" v-model="attribute.type">
                            <el-option value="number" label="数字"></el-option>
                            <el-option value="text" label="文字"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="单位" prop="unit">
                        <el-input type="text" name="unit" v-model="attribute.unit"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addAttribute">保存添加</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

        </el-main>
    </el-container>
</template>

<script>
    import tinymceEditor from '@/components/tinymce-editor.vue'
    import common from '@/api/common';

    export default {
        components: {
            tinymceEditor
        },
        data: function () {
            return {
                addToken: null,
                addLoading: false,
                loading: false,
                type: null,//发布的类型
                tagList: [],
                tagInputVisible: false,
                tagInputValue: '',
                visible: false,
                activeStep: 0,
                delivery: false,
                dynamic: {
                    visibility: '1'
                },
                attribute: {
                    type: "text"
                },
                attributeRules: {
                    value: [
                        {required: true, message: '请输入属性值', trigger: 'change'}
                    ]
                },
                addAttributeRules: {
                    name: [
                        {required: true, message: '请输入属性名称', trigger: 'blur'},
                        {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
                    ],
                    value: [
                        {required: true, message: '请输入属性值', trigger: 'change'}
                    ],
                    type: [
                        {required: true, message: '请选择属性类型', trigger: 'change'}
                    ],
                    unit: [
                        {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'change'}
                    ]
                },
                attributeList: [],
                disabled: false,
                industryCategoryData: [],
                areaList: [],
                typeList: [],
                dynamicRules: {
                    industryCategory: [
                        {required: true, message: '请选择所属行业', trigger: 'change'}
                    ],
                    type: [
                        {required: true, message: '请选择类型', trigger: 'change'}
                    ],
                    title: [
                        {required: true, message: '请输入标题', trigger: 'change'},
                        {min: 1, max: 49, message: '最大49个字符', trigger: 'change'}
                    ],
                    content: [
                        {required: true, message: '请输入描述', trigger: 'change'}
                    ],


                },
                titleNumber: 49,
                headerTitle: "发布",
                placeholderList: [
                    '一句话完整的描述你可以提供什么',
                    '一句话完整的描述你需要什么',
                    '一句话完整的描述你的问题',
                    '一句话完整的描述你的融资项目或方案',
                    '输入你公告的标题',
                    '输入你的作品名称',
                    '一句话完整的描述你的经验',
                    '说说你想吐槽的',
                    '说说你的分享',
                    '输入你的文章的标题'
                ]

            }
        },
        methods: {
            getInitData() {
                this.loading = true;
                let i = 0
                common.industryCategoryQueryAll().then(res => {
                    this.industryCategoryData = res.data;
                    i++;
                    if (i >= 3) {
                        this.loading = false;
                    }
                });
                common.areaQueryAll().then(res => {
                    this.areaList = res.data;
                    i++;
                    if (i >= 3) {
                        this.loading = false;
                    }
                });
                common.dictionaryTypeQueryList(2).then(res => {
                    this.typeList = res.data;
                    this.changHeader();
                    i++;
                    if (i >= 3) {
                        this.loading = false;
                    }
                });
            },
            /***
             * 下一步
             * */
            next() {
                this.$refs['stepForm' + this.activeStep].validate((valid) => {
                    if (valid) {
                        if (this.activeStep >= 3) {
                            this.save();
                            return;
                        }
                        if (this.activeStep == 0) {
                            //获取默认属性
                            this.getDefaultAttribute();
                        }
                        this.activeStep++;
                    } else {

                    }
                });

            },
            pre() {
                if (this.activeStep > 0) {
                    this.activeStep--;
                }
            },
            save() {
                this.addLoading = true;
                let params = JSON.parse(JSON.stringify(this.dynamic));
                //保存上传
                params.addToken = this.addToken;
                params.attributeList = [];
                this.attributeList.forEach(attr => {
                    let value = attr.value;
                    let code = ''
                    if (attr.valueType == 'select') {
                        attr.dataList.forEach(d => {
                            if (d.id == attr.value) {
                                value = d.name;
                                code = d.id;
                            }
                        })
                    }
                    params.attributeList.push({
                        name: attr.name,
                        value: value,
                        code: code,
                        attributeId: attr.id,
                        unit: attr.unit,
                        valueType: attr.valueType,
                        type: attr.custom ? 0 : 1
                    })
                })
                this.industryCategoryData.forEach(ic => {
                    if (ic.code == params.industryCategory[0]) {
                        params.parentCategoryCode = ic.code;
                        params.parentCategoryName = ic.name;
                        if (params.industryCategory[1]) {
                            ic.sublist.forEach(ics => {
                                params.subCategoryCode = ics.code;
                                params.subCategoryName = ics.name;
                            })
                        }
                    }
                })
                if (this.dynamic.area) {
                    this.areaList.forEach(a => {
                        if (a.code == this.dynamic.area[0]) {
                            params.provinceCode = a.code;
                            params.provinceName = a.name;
                            if (this.dynamic.area[1]) {
                                a.sublist.forEach(as => {
                                    params.cityCode = as.code;
                                    params.cityName = as.name;
                                })
                            }
                        }
                    })
                }

                params.areaList = null;
                params.industryCategory = null;
                params.tagList = this.tagList;
                this.$post("dynamic/add", params).then(res => {
                    this.addLoading = false;
                    this.$notify({offset: 60, title: '成功', message: '发布成功', type: 'success'})
                    this.$router.push("/dynamic-share");
                }).catch(() => {
                    this.addLoading = false;
                })
            },
            /**
             * 添加属性
             * */
            addAttribute() {
                this.$refs.addAttributeForm.validate((valid) => {
                    if (valid) {
                        this.attribute.custom = true;//自定义
                        this.attribute.isRequired = 1;//必需填
                        this.attributeList.push(this.attribute)
                        this.attribute = {
                            type: 'text'
                        };
                        this.visible = false;
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            removeAttribute(index) {
                this.$confirm('确定删除属性:' + this.attributeList[index].name + '?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.attributeList.splice(index, 1)
                })
            },
            showAttribute() {
                this.visible = true;
            },
            /**
             * 校验属性值
             * @param rule
             * @param value
             * @param callback
             */
            validatorValue(rule, value, callback) {
                let index = rule.field;
                let attr = this.attributeList[index];
                value = attr.value;
                if (attr.isRequired == 1 && (value === null || value === undefined || value === '')) {
                    callback(new Error('请输入' + this.attributeList[index].name));
                } else if (attr.regularExpression && value) {
                    let reg = new RegExp(attr.regularExpression);
                    if (!reg.test(value)) {
                        callback(new Error(attr.errorMessage));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            },
            back() {
                this.$router.push("/")
            },
            changHeader() {
                if (this.typeList[this.dynamic.type - 1] == undefined) {
                    this.headerTitle = '发布';
                } else {
                    this.headerTitle = "发布" + this.typeList[this.dynamic.type - 1].name;
                }
            },
            handleTagClose(tag) {
                this.tagList.splice(this.tagList.indexOf(tag), 1);
            },

            showTagInput() {
                this.tagInputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },

            handleTagInputConfirm() {
                let flag = true;
                if (this.tagList.length >= 5) {
                    this.$notify({title: '错误', message: '标签个数不能超过5个', type: 'error'})
                    flag = false;
                }

                let inputValue = this.tagInputValue;
                if (inputValue) {
                    if (inputValue.length > 20) {
                        this.$notify({title: '错误', message: '标签长度不能超过20', type: 'error'})
                        flag = false;
                    }
                    this.tagList.forEach(item => {
                        if (inputValue === item) {
                            this.$notify({title: '错误', message: '请勿重复添加', type: 'error'})
                            flag = false;
                        }
                    })
                    if (flag) {
                        this.tagList.push(inputValue);
                    }
                }
                this.tagInputVisible = false;
                this.tagInputValue = '';
            },
            getDefaultAttribute() {
                this.loading = true;
                this.$post("/dynamic/defaultAttribute/queryList", {
                    type: this.dynamic.type,
                    parentCategoryCode: this.dynamic.industryCategory[0],
                    subCategoryCode: this.dynamic.industryCategory[1]
                }).then(res => {
                    res.data.forEach(attr => {
                        attr.value = attr.defaultValue;
                        if (attr.valueType == 'select' && attr.dictionaryTypeId) {
                            //获取下拉列表
                            attr.dataList = [];
                            common.dictionaryQueryByType(attr.dictionaryTypeId).then(res => {
                                attr.dataList = res.data;
                            });
                        }
                    })
                    this.attributeList = res.data;
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                })
            }
        },
        mounted() {
            let params = this.$route.query;
            if (params.type) {
                this.dynamic.type = params.type;
                this.type = params.type;
            }
            this.getInitData();
            //获取权限
            this.$post("/dynamic/getAddToken").then(res => {
                this.addToken = res.data;
            })
        }
    }
</script>
<style>
    .header-container .el-page-header {
        line-height: 60px
    }

    .header-container .el-page-header__content {
        color: #fff;
    }

    .add-dynamic {
    }

    .add-dynamic .el-upload--picture-card {
        width: 67px;
        height: 67px;
        line-height: 67px;
    }

    .add-dynamic .el-upload--picture-card i {
        font-size: 22px;
    }

    .add-dynamic .el-upload-list--picture-card .el-upload-list__item {
        width: 67px;
        height: 67px;
        line-height: 67px;
    }

    .add-dynamic .el-upload-list--picture-card .el-upload-list__item-actions {
        font-size: 18px;
    }

    .add-dynamic .attribute-name {
        background-color: #f6f6f6;
    }

    .add-dynamic .el-steps {
        margin-bottom: 20px;
    }

    .add-dynamic .el-alert {
        margin-bottom: 20px;
    }

    .add-dynamic .el-form-item .el-link {
        margin-left: 10px;
        vertical-align: bottom;
    }

    .add-dynamic .title-form-item {
        line-height: 40px;
        font-size: 16px;
    }

    .add-dynamic .el-form-item .el-link i {
        font-size: 18px;
    }

    .add-attribute-form .el-input {
        width: 215px;
    }

    .add-dynamic .attribute-form {
        width: 820px;
    }

    .add-dynamic .attribute-form .el-form-item.el-form-item--small {
        width: 400px;
    }

    .titleNumber {
        position: absolute;
        right: 5px;
    }

    .el-tag {
        margin-right: 10px;
    }

    .button-new-tag {
    }

    .input-new-tag {
        width: 90px;
        vertical-align: bottom;
    }


    .ck-content {
        height: 500px;
    }

</style>